//
//  CQOAuthViewController.m
//  01-OC微博
//
//  Created by 陈乾 on 15/11/2.
//  Copyright © 2015年 陈乾. All rights reserved.
//

#import "CQOAuthViewController.h"
#import "AFNetworking.h"
#import "MBProgressHUD+MJ.h"
#import "CQAccount.h"
#import "CQAccountTool.h"
#import "CQRootTool.h"

#define CQClient_id @"1458512798"
#define CQRedirect_uri @"http://www.baidu.com/"
#define CQClient_secret @"8f254231bd2aef248cb2b64b19b9eff6"
@interface CQOAuthViewController ()<UIWebViewDelegate>

@end

@implementation CQOAuthViewController

//这里拦截设置成webView 不需要设置frame
-(void)loadView {
   
    //创建
    UIWebView *webView = [[UIWebView alloc] init];
    //拦截
    self.view = webView;
    //设置代理
    webView.delegate = self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIWebView *webView = (UIWebView*)self.view;
    
    NSString *baseUrl = @"https://api.weibo.com/oauth2/authorize";
    NSString *client_id = @"1458512798";
    NSString *redirect_uri = @"http://www.baidu.com/";
    //格式：https://api.weibo.com/oauth2/authorize?client_id=1458512798&redirect_uri=http://www.baidu.com/
    //创建urlStr
    NSString *urlStr = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@",baseUrl,client_id,redirect_uri];
    //创建URL
    NSURL * url = [NSURL URLWithString:urlStr];
    //创建request
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //加载request
    [webView loadRequest:request];
    
}

#pragma mark -代理
//加载开始
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    [MBProgressHUD showSuccess:@"登陆中.."];
    
}

//加载完成
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [MBProgressHUD hideHUD];
}

//是否加载request 加载前会调用
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
   
    NSString *urlStr = request.URL.absoluteString;
    
    //获取code
    NSRange range = [urlStr rangeOfString:@"code="];
    
    if (range.length) {
        //不为空
        //就截取code=后面的内容
        NSString *code = [urlStr substringFromIndex:range.location + range.length];
        //用code 换取 access_Token
        [self getAccessTokenWithCode:code];
        
        //不让跳转到百度页面
        return  NO;
    }
    
    
    
    return  YES;
}
/*
 
 必选	类型及范围	说明
 client_id	true	string	申请应用时分配的AppKey。
 client_secret	true	string	申请应用时分配的AppSecret。
 grant_type	true	string	请求的类型，填写authorization_code
 
 grant_type为authorization_code时
 必选	类型及范围	说明
 code	true	string	调用authorize获得的code值。
 redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
 */

- (void)getAccessTokenWithCode:(NSString *)code {
  
    NSString *url = @"https://api.weibo.com/oauth2/access_token";
    
    NSDictionary *params = @{
                              @"client_id":CQClient_id,
                              @"client_secret":CQClient_secret,
                              @"grant_type": @"authorization_code",
                              @"code":code,
                              @"redirect_uri":CQRedirect_uri
                                    
                                    };
    //请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    
   [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
       NSLog(@"%@",responseObject);
       
       //字典转模型
       CQAccount *account = [CQAccount accountWithDic:responseObject];
       
       //保存到沙盒
        [CQAccountTool saveAccount:account];
      
       //选中根控制器
       [CQRootTool choseNewFeatureViewController:CQKeyWindow];
       
       
   } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       NSLog(@"%@",error);
   }];
 
}





@end
